#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if (left == right)return head;
        ListNode* pre = nullptr;
        ListNode* star = nullptr;
        ListNode* end = nullptr;
        ListNode* cur = head;
        ListNode* l = nullptr;
        ListNode* r = nullptr;
        int pos = 1;
        while (cur) {
            if (pos == left - 1) {
                star = cur;
            }
            if (pos == right + 1) {
                end = cur;
            }
            pos++;
            cur = cur->next;
        }
        // cout<<star->val<<" "<<end->val<<endl;
        pos = 1;
        cur = head;
        while (cur) {
            if (pos == left)r = cur;
            if (pos == right)l = cur;
            if (pos > left && pos <= right) {
                ListNode* t = cur->next;
                cur->next = pre;
                pre = cur;
                cur = t;
            }
            else {
                pre = cur;
                cur = cur->next;
            }
            pos++;
        }
        //if(l)cout<<l->val<<" ";
        // if(r)cout<<r->val<<endl;
        if (star)star->next = l;
        if (r)r->next = end;
        if (left == 1)return l;
        return head;

    }
};